import { Injectable } from '@angular/core';
import { DomService, DgControl, FormBasicService } from '@farris/designer-services';
import { ControlTreeNode, ControlTreeNodeType } from '../entity/tree-node';
import { ControlTreeNodeBuilderService } from './tree-node-builder.service';

@Injectable()
export class ControlTreeBuilderService {

  private nodeBuilderService: ControlTreeNodeBuilderService;

  /** 控件树节点-平铺 */
  plainControlTreeNodes = [];

  constructor(
    private domService: DomService,
    private formbasicService: FormBasicService) {
    this.nodeBuilderService = new ControlTreeNodeBuilderService(domService);
  }

  /**
   * 表单对象映射为树结构
   * @param formData 表单Dg对象
   */
  public mappingFormDataToTree(domJson: any): ControlTreeNode[] {
    if (!domJson) {
      return;
    }
    this.plainControlTreeNodes = [];

    // 表单顶层节点
    const frameId = this.formbasicService.formMetaBasicInfo.id;
    const frameNode: ControlTreeNode = {
      data: {
        id: frameId,
        name: '页面',
      },
      rawElement: domJson,
      type: ControlTreeNodeType.Frame,
      children: [],
      expanded: true,
      index: 0,
      parentNodeId: null,
      hideContextMenuIcon: true,
      controlIcon: 'fd-i-Family fd_pc-Module',
      tips: '页面[' + frameId + ']'

    };
    if (this.formbasicService.envType === 'mobileDesigner') {
      const pageComponents = domJson.module.components.filter(component => component.type === 'Component' && component.componentType === 'Page');
      const pageComponentNodes = pageComponents.map(component => this.createComponentNode(component, 0, null, false));
      frameNode.children = pageComponentNodes;
      this.plainControlTreeNodes.push(frameNode);
      frameNode.data.name = domJson.module.name
      return [frameNode];
    }
    const rootComponent = domJson.module.components[0];
    const rootComponentNode = this.createComponentNode(rootComponent, 0, null);
    frameNode.children = [rootComponentNode];

    this.plainControlTreeNodes.push(frameNode);

    return [frameNode];
  }

  private recursionElements(parentElement: any): ControlTreeNode[] {
    const elements = parentElement.contents as any[];
    const parentNodeId = parentElement.id;

    const newComponentNodeList: ControlTreeNode[] = [];

    elements.forEach((element: any, index: number) => {
      let newComponentNode: ControlTreeNode;
      let nodeRefObject;

      if (element.type === 'ComponentRef') {
        const childComponentNode = this.domService.getComponentById(element.component);
        newComponentNode = this.createComponentNode(childComponentNode, index, parentNodeId);
        newComponentNodeList.push(newComponentNode);

        this.plainControlTreeNodes.push(newComponentNode);
      } else {
        // 获取树节点名称
        const nodeName = this.nodeBuilderService.getNodeName(element, parentElement);
        newComponentNode = {
          data: {
            id: element.id,
            name: nodeName,
          },
          rawElement: element,
          children: [],
          expanded: true,
          type: ControlTreeNodeType.Control,
          index,
          parentNodeId,
          controlIcon: this.nodeBuilderService.getControlIconClass(element),
          dependentParentControl: DgControl[element.type] && DgControl[element.type].dependentParentControl,
          tips: nodeName + '[' + element.id + ']'
        };
        if (element.contents) {
          nodeRefObject = this.recursionElements(element);
          if (nodeRefObject.length) {
            newComponentNode.children = nodeRefObject;
          }
        }

        newComponentNodeList.push(newComponentNode);
        this.plainControlTreeNodes.push(newComponentNode);

        // 列表弹出编辑
        if ((DgControl.DataGrid && DgControl.DataGrid.type === element.type) && element.enableEditByCard !== 'none' && element.modalComponentId) {
          const modalCmp = this.domService.getComponentById(element.modalComponentId);
          if (modalCmp) {
            const modalComponentNode = this.createComponentNode(modalCmp, index, parentNodeId);
            newComponentNodeList.push(modalComponentNode);

            this.plainControlTreeNodes.push(newComponentNode);
          }

        }

      }
    });

    return newComponentNodeList;


  }
  private createComponentNode(element: any, elementIndex: number, parentNodeId: string, expanded = true): ControlTreeNode {
    // 组件子控件节点，默认为空数组。
    let controlsNodes: ControlTreeNode[] = [];
    // 如果组件下包含子元素，构造子控件节点数组。
    if (element.contents) {
      controlsNodes = this.recursionElements(element);
    }
    // 获取树节点名称（mock，待集成控件元数据后删除）
    const nodeName = this.nodeBuilderService.getNodeName(element);

    // 构造组件节点
    const newComponentNode: ControlTreeNode = {
      data: {
        id: element.id,
        name: nodeName,
      },
      rawElement: element,
      children: controlsNodes,
      expanded: expanded,
      type: ControlTreeNodeType.Component,
      index: elementIndex,
      parentNodeId,
      controlIcon: this.nodeBuilderService.getControlIconClass(element),
      tips: nodeName + '[' + element.id + ']'
    };
    return newComponentNode;
  }

}
